import { fileURLToPath, URL } from 'node:url'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import UnoCSS from 'unocss/vite'
import * as path from 'path'
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
import { visualizer } from 'rollup-plugin-visualizer'
import autoprefixer from 'autoprefixer'
import cssnano from 'cssnano'
import litePreset from 'cssnano-preset-lite'
import { name } from './package.json'

const root = process.cwd()

//
const FPI_ASSETS_VERSION = '1.0.0'

// https://vite.dev/config/
export default defineConfig(({ command, mode }) => {
    let env = {} as any
    const isBuild = command === 'build'
    if (!isBuild) {
        env = loadEnv(process.argv[3] === '--mode' ? process.argv[4] : process.argv[3], root)
    } else {
        env = loadEnv(mode, root)
    }
    console.log(env)

    return {
        define: {
            __APP_FPI_ASSETS_VERSION__: JSON.stringify(FPI_ASSETS_VERSION),
        },

        base: './',

        resolve: {
            alias: {
                '@': fileURLToPath(new URL('./src', import.meta.url)),
            },
        },

        server: {
            port: 3089,
            open: true,
            proxy: {
                '/api': {
                    target: env.VITE_API_URL,
                    rewrite: path => path.replace(/^\/api/, ''),
                    changeOrigin: true,
                    secure: false,
                },
            },
        },

        plugins: [
            vue({
                template: {
                    compilerOptions: {
                        isCustomElement: tag => /^micro-app/.test(tag),
                    },
                },
            }),
            // 自动导入
            AutoImport({
                resolvers: [ElementPlusResolver({ importStyle: false })],
                imports: ['vue', 'vue-router', 'pinia'],
                dts: 'auto-imports.d.ts',
                eslintrc: {
                    enabled: false,
                    filepath: '.eslintrc-auto-import.json',
                    globalsPropValue: true,
                },
            }),
            // 自动导入组件 目前只导入ElementPlus
            Components({
                dirs: [],
                resolvers: [ElementPlusResolver({ importStyle: false })],
            }),
            // svg插件
            createSvgIconsPlugin({
                iconDirs: [path.resolve(process.cwd(), 'src/assets/svg-icons')],
                symbolId: '[name]',
            }),
            // 打包分析插件
            visualizer({
                filename: 'dist/stats.html',
            }),
            UnoCSS(),
        ],

        build: {
            outDir: env.VITE_OUT_DIR,
            target: ['chrome78'],
            minify: true,
            cssMinify: false, // 必须为false
        },

        css: {
            preprocessorOptions: {
                scss: { api: 'modern-compiler' },
            },
            //
            postcss: {
                plugins: [
                    // 配合 cssMinify:false 相当于重写的css压缩方式，否则会移除css注释
                    cssnano({
                        preset: litePreset({ discardComments: false }),
                        plugins: [autoprefixer],
                    }),
                ],
            },
        },
    }
})
